package com.health_and_exercise.healthandexercisev1.app;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.CountDownTimer;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;

import java.util.Calendar;


public class UserInfoInputActivity extends ActionBarActivity {
    private int age;
    private int userTargetSteps;
    private int heightFoot;
    private int heightInch;
    private float weight;
    private long targetTimeMilli;
    private TextView ageView;
    private CountDownTimer countDownTimer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_info_input);
        ageView = (TextView) findViewById(R.id.userBirthDatePickerTextView);
        final EditText editText = (EditText) findViewById(R.id.editText);
        editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                boolean handled = false;
                if (actionId == EditorInfo.IME_ACTION_SEND) {
                    System.out.println("editText = " + editText.getText().toString());
                    userTargetSteps = Integer.valueOf(editText.getText().toString());
                    handled = true;
                }
                return handled;
            }
        });


        if (savedInstanceState!= null && savedInstanceState.containsKey("AGE")) {
            age = savedInstanceState.getInt("AGE");
            ageView.setText("User's age is: " + String.valueOf(age));
        } else {
            age = 0;
        }

        if (savedInstanceState!= null && savedInstanceState.containsKey("TARGET_TIME")) {
            targetTimeMilli = savedInstanceState.getLong("TARGET_TIME");
            ageView.setText("Target time stamp: " + String.valueOf(targetTimeMilli));
        } else {
            targetTimeMilli = 0;
        }

        Button button = (Button) findViewById(R.id.userBirthDatePickerButton);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showDatePickerDialog(view, true /* birthday */);
            }
        });

        Button buttonTargetTime = (Button) findViewById(R.id.userTargetTimePickerButton);
        buttonTargetTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showDatePickerDialog(view, false /* target date */);
            }
        });
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("AGE", age);
        outState.putLong("TARGET_TIME", targetTimeMilli);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.user_info_input, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void showTimePickerDialog(View v, Calendar selectedDate) {
        DialogFragment newFragment = new TimePickerFragment(selectedDate);
        newFragment.show(getSupportFragmentManager(), "timePicker");
    }

    public class TimePickerFragment extends DialogFragment
            implements TimePickerDialog.OnTimeSetListener {
        private Calendar selectedDate;

        public TimePickerFragment(Calendar selectedDate) {
            this.selectedDate = selectedDate;
        }

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            // Use the current time as the default values for the picker
            final Calendar c = Calendar.getInstance();
            int hour = c.get(Calendar.HOUR_OF_DAY);
            int minute = c.get(Calendar.MINUTE);

            // Create a new instance of TimePickerDialog and return it
            return new TimePickerDialog(getActivity(), this, hour, minute,
                    DateFormat.is24HourFormat(getActivity()));
        }

        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

            // Do something with the time chosen by the user

            Calendar dateAndTime = Calendar.getInstance();
            dateAndTime.set(selectedDate.get(Calendar.YEAR), selectedDate.get(Calendar.MONTH),
                selectedDate.get(Calendar.DAY_OF_MONTH), hourOfDay, minute);

            targetTimeMilli = dateAndTime.getTimeInMillis();

            Intent toMainActivity = new Intent(getApplicationContext(), MainActivity.class);
            toMainActivity.putExtra("TARGET_TIME", targetTimeMilli);
            toMainActivity.putExtra("AGE", age);
            toMainActivity.putExtra("TARGET_STEP", userTargetSteps);
            Log.d("UserInfoInputActivity", "targetSteps = " + String.valueOf(userTargetSteps));
            ageView.setText("Target time stamp: " + String.valueOf(targetTimeMilli));
            try {
                startActivity(toMainActivity);
            } catch (Exception e) {
                Log.wtf(e.toString(), e);
            }
        }
    }

    public void showDatePickerDialog(View v, boolean isBirthday) {
        DialogFragment newFragment = new DatePickerFragment(isBirthday);
        newFragment.show(getSupportFragmentManager(), "datePicker");
    }

    public class DatePickerFragment extends DialogFragment
            implements DatePickerDialog.OnDateSetListener {
        private boolean isBirthday;
        private boolean alreadyRan;

        public DatePickerFragment(boolean isBirthday) {
            this.isBirthday = isBirthday;
            this.alreadyRan = false;
        }

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            // Use the current date as the default date in the picker
            final Calendar c = Calendar.getInstance();
            int year = c.get(Calendar.YEAR);
            int month = c.get(Calendar.MONTH);
            int day = c.get(Calendar.DAY_OF_MONTH);

            // Create a new instance of DatePickerDialog and return it
            return new DatePickerDialog(getActivity(), this, year, month, day);
        }

        public void onDateSet(DatePicker view, int year, int month, int day) {
            // Do something with the date chosen by the user
            if (!alreadyRan) {
                alreadyRan = true;
                Calendar today = Calendar.getInstance();
                Calendar selectedDate = Calendar.getInstance();
                selectedDate.set(year, month, day);

                if (isBirthday) {
                    age = today.get(Calendar.YEAR) - selectedDate.get(Calendar.YEAR);

                    if (today.get(Calendar.DAY_OF_YEAR) < selectedDate.get(Calendar.DAY_OF_YEAR)){
                        age--;
                    }

                    ageView.setText("User's age is: " + String.valueOf(age));
                } else {
                    showTimePickerDialog(view, selectedDate);
                }
            }
        }
    }

}
